"""

open interest : 开仓量
"""

from binance.client import Client
import pandas as pd
import datetime

# 初始化客户端（无需API密钥即可获取公开数据）
client = Client()


def get_futures_open_interest(symbol):
    """
    获取永续合约持仓量
    """
    try:
        # 获取持仓量信息
        oi_data = client.futures_open_interest(symbol=symbol)
        oi_data["datetime"] = datetime.datetime.fromtimestamp(int(oi_data['time'])/1000).strftime('%Y-%m-%d %H:%M:%S')
        return oi_data
    except Exception as e:
        print(f"Error: {e}")
        return None


def get_top_trader_long_short_ratio(symbol, period='5m'):
    """
    获取大户持仓多空比
    """
    try:
        ratio_data = client.futures_top_longshort_position_ratio(
            symbol=symbol,
            period=period
        )
        for x in ratio_data:
            x["datetime"] = datetime.datetime.fromtimestamp(x['timestamp']/1000).strftime('%Y-%m-%d %H:%M:%S')
        return ratio_data
    except Exception as e:
        print(f"Error: {e}")
        return None


# 使用示例
if __name__ == "__main__":
    symbol = "BTCUSDT"

    # 获取持仓量
    open_interest = get_futures_open_interest(symbol)
    print(f"{symbol} 持仓量: {open_interest}")

    # 获取大户多空比
    long_short_ratio = get_top_trader_long_short_ratio(symbol)
    print(f"{symbol} 大户多空比: {long_short_ratio}")